package cn.com.main;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java目录扫描程序
 *
 * @author LiuGuodong
 * @date 2024/03/04
 */
public class DirectoryScanner {

    public static List<String> scanDirectoryForImport(String directoryPath, String importStatement) {
        List<String> matchingFiles = new ArrayList<>();

        try {
            List<Path> collect = Files.walk(Paths.get(directoryPath))
                    .filter(Files::isRegularFile).collect(Collectors.toList());
            for (Path filePath : collect) {
                File file = filePath.toFile();
                if (file.getName().endsWith(".java")) {
                    try {
                        String content = new String(Files.readAllBytes(filePath));
                        // 使用正则表达式搜索 import 语句
                        if (content.matches("(?s).*\\b" + importStatement + "\\b.*")) {
                            matchingFiles.add(file.getName());
                        }
                    } catch (IOException e) {
                        System.err.println("Error reading file: " + file.getAbsolutePath() + ": " + e.getMessage());
                    }
                }
            }

        } catch (IOException e) {
            System.err.println("Error scanning directory: " + directoryPath + ": " + e.getMessage());
        }

        return matchingFiles;
    }

    public static void main(String[] args) {
        String directoryPath = "E:/cloud_star/project_code/rightcloud/pf/rightcloud-parent/rightcloud-bss/src/main/java/cn/com/cloudstar/rightcloud/bss";
        String importStatement = "import cn.com.cloudstar.rightcloud.bss.module.access.mapper.SysUserMapper";

        List<String> matchingFiles = scanDirectoryForImport(directoryPath, importStatement);
        System.out.println("Matching files:");
        for (String filePath : matchingFiles) {
            System.out.println(filePath);
        }
    }
}
